<?php

namespace App\Services;

use App\Common\Enums\LetterStatusEnum;
use App\Common\Enums\LetterTypeEnum;
use App\Common\Enums\SystemAliasEnum;
use App\Common\Helpers\Functions;
use App\Common\Services\BaseService;
use App\Common\Tools\CustomException;
use App\Models\LetterModel;

class LetterService extends BaseService
{
    /**
     * constructor.
     */
    public function __construct(){
        parent::__construct();

        $this->model = new LetterModel();
    }

    /**
     * @param $data
     * @return bool
     * @throws \App\Common\Tools\CustomException
     * 创建
     */
    public function create($data){
        $this->validRule($data, [
            'system_alias' => 'required',
            'source_admin_id' => 'required',
            'target_admin_id' => 'required',
            'letter_type' => 'required',
        ]);

        Functions::hasEnum(SystemAliasEnum::class, $data['system_alias']);
        Functions::hasEnum(LetterTypeEnum::class, $data['letter_type']);

        if($data['letter_type'] == LetterTypeEnum::MATERIAL_RECOMMEND){
            if(empty($data['extends']['recommend_id'])){
                throw new CustomException([
                    'code' => 'RECOMMEND_ID_IS_EMPTY',
                    'message' => '站内信类型为素材推荐时, 素材推荐id不能为空'
                ]);
            }
        }elseif($data['letter_type'] == LetterTypeEnum::APPROVAL){
            if(empty($data['extends']['approval_id'])){
                throw new CustomException([
                    'code' => 'APPROVAL_ID_IS_EMPTY',
                    'message' => '站内信类型为审批时, 审批id不能为空'
                ]);
            }
        }elseif($data['letter_type'] == LetterTypeEnum::MESSAGE){
            if(empty($data['extends']['message_content'])){
                throw new CustomException([
                    'code' => 'MESSAGE_CONTENT_IS_EMPTY',
                    'message' => '站内信类型为消息时, 消息内容不能为空'
                ]);
            }
        }else{
            throw new CustomException([
                'code' => 'PLEASE_WRITE_LETTER_CREATE_CODE',
                'message' => '请书写站内信创建代码',
                'data' => [
                    'letter_type' => $data['letter_type'],
                ],
            ]);
        }

        $this->model->system_alias = $data['system_alias'];
        $this->model->source_admin_id = $data['source_admin_id'];
        $this->model->target_admin_id = $data['target_admin_id'];
        $this->model->letter_type = $data['letter_type'];
        $this->model->letter_status = LetterStatusEnum::UNREAD;
        $this->model->extends = $data['extends'];

        $ret = $this->model->save();

        return $ret;
    }
}
